import flask, os,sys,time
from flask import request, send_from_directory
import pandas as pd
from MongoDbHandler import MongoDbHandler
from threading import Thread

server = flask.Flask(__name__)
mongoSession = MongoDbHandler('127.0.0.1', 'admin', 'admin')


def update_kw(path):
    # path_dir = 'C:/search_top/'
    # file_name=os.listdir(path_dir)[0]
    # path=os.path.join(path_dir,file_name)
    path_dir, file = os.path.split(path)
    df = pd.read_excel(path, header=None)
    # print(df)
    kw_li = df[0].dropna(axis=0, how='all').tolist()[1:]
    pt_li = df[1].dropna(axis=0, how='all').tolist()[1:]
    pt2_li = df[2].dropna(axis=0, how='all').tolist()[1:]
    # print(pt_li,pt2_li)
    site_dict = dict(zip(pt_li, pt2_li))
    user = df[3].dropna(axis=0, how='all').tolist()[-1]
    email_li = df[4].dropna(axis=0, how='all').tolist()[1:]
    history = df[5].dropna(axis=0, how='all').tolist()[-1]
    # print(kw_li,site_dict,user,email_li,history)
    kw_dict = {}
    t = time.time()
    ymd = time.strftime('%Y-%m-%d', time.localtime(t))
    kw_dict['kw'] = kw_li
    kw_dict['sites'] = site_dict
    kw_dict['user'] = user
    kw_dict['email'] = email_li
    kw_dict['history'] = history
    kw_dict['time'] = int(t)
    kw_dict['年月日'] = ymd
    user_dict = {'user': user}
    # print(kw_dict)
    # A为mongodb的name,B为用户名，C为密码
    # result = mongoSession.find_all("jk", "keyword")  # D为数据库名，E为集合名
    mongoSession.delete_many("jk", "keyword",user_dict)
    mongoSession.insert_one("jk", "keyword", kw_dict)  # D为数据库名，E为集合名
    print('关键词插入成功')

# post方法：上传文件的
@server.route('/upload', methods=['post'])
def upload():
    fname = request.files.get('file')  #获取上传的文件
    if fname and '.xls' in fname.filename:
        path_dir=r'C:/search_top/'
        file_li=os.listdir(path_dir)
        for f in file_li:
            os.remove(path_dir+f)
        t = time.strftime('%Y%m%d-%H%M%S-')
        new_fname = path_dir + t + fname.filename
        fname.save(new_fname)  #保存文件到指定路径
        update_kw(new_fname)
        return '{"code": "ok"}'
    else:
        return '{"msg": "请上传表格文件！"}'

@server.route('/find', methods=['get'])
def find():
    return 'ok'


server.run(port=8000, debug=True)